<?php

namespace app\article\controller;

use \app\check\controller\Check;
use app\common\cachemodel\ArticleCommentGood;
use app\common\cachemodel\ArticleRead;
use app\common\cachemodel\ZlUserVip;
use app\common\lib\exception\ApiException;
use app\common\model\Article;
use app\common\model\ArticleCollect;
use app\common\model\ArticleComment;
use app\common\model\ArticleCommentReply;
use app\common\model\ArticleGood;
use \think\Db;
use \think\Cache;
use think\response\Json;

// 获取文章接口
class Index extends Check
{
    /**
     * @var ArticleComment
     */
    private $CommentModel;
    /**
     * @var ArticleCommentReply
     */
    private $ReplyModel;

    public function _initialize()
    {
        parent::_initialize();

        $this->CommentModel = new ArticleComment();
        $this->ReplyModel = new ArticleCommentReply();
    }

    /**
     * 查看文章列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $cid = input('param.cid/d', 1);

        $map['a.cid'] = $cid;
        $map['a.status'] = 1;

        $data = Db::table('wechatadmin.system_article')->alias('a')
            ->field('a.id,a.cid,a.title,a.introduction,u.name author,u.thumb avatar,a.thumb,a.publish_time,a.good,a.collect,(a.read+a.read_base) `read`,t.name type_name,t.name_en type_name_en')
            ->join('wechatadmin.zhunle_article_author u', 'a.uid=u.id', 'INNER')
            ->join('wechatadmin.system_article_type t', 't.id=a.tid', 'LEFT')
            ->where($map)
            ->whereTime('a.publish_time', '<', time())// 查看当前时间以前的文章  预发布文章不显示
            ->order('a.publish_time DESC')
            ->paginate(10, false, ['query' => request()->param()])->toArray();
        // 添加 当前文章当前用户点赞 和 收藏状态
//        $data = json_decode(json_encode($data),true);
        foreach ($data['data'] as $k => $d)
        {
            if (!input('param.access_token'))
            {
                $data['data'][$k]['publish_time'] = strtotime($data['data'][$k]['publish_time']);
            }

            $data['data'][$k]['good_status'] = false;
            $data['data'][$k]['collect_status'] = false;
            //  点赞收藏
            $data['data'][$k]['good'] += floor($data['data'][$k]['read'] / 30);
            $data['data'][$k]['collect'] += floor($data['data'][$k]['read'] / 250);

            $good = Db::table('wechatadmin.system_article_good')->where(['aid' => $d['id'], 'ucid' => $this->user['uc_id']])->find();

            $collect = Db::table('wechatadmin.system_article_collect')->where(['aid' => $d['id'], 'ucid' => $this->user['uc_id']])->find();

            if ($good != NULL) $data['data'][$k]['good_status'] = true;
            if ($collect != NULL) $data['data'][$k]['collect_status'] = true;
        }

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 查看文章详情 - 已加缓存
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \Exception
     */
    public function details()
    {
        $access_token = input('access_token/s', '');// 处理旧版文章详情接口 文章发布时间为datetime

        $aid = input('param.id/d', 0);
        $map = [
            'id' => $aid,
            'uid' => $this->user['id'],
            'ucid' => $this->user['uc_id'],
            'is_old' => $access_token == '' ? true : false,
        ];
        $access_token == '' ? $time_type = 0 : $time_type = 1;
        $data = (new Article())->getArticleDetails($this->user['id'], $map, $time_type);
        if ($data)
        {
            //内容已读
            (new ArticleRead())->saveData($this->user['id'], 1, $aid);
            unset($data['comment']);
            return show(config('code.success'), '加载成功', $data);
        }
        return show(config('code.error'), '内容不存在');
    }

    /**
     * 文章点赞接口 - 已加缓存
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \Exception
     */
    public function good()
    {
        $aid = input('param.id');
        $map = [
            'id' => $aid,
            'uid' => $this->user['id'],
            'ucid' => $this->user['uc_id'],
        ];

        $validate = validate('Article');

        if (!$validate->scene('index')->check($map))
        {
            return show(config('code.error'), (string)$validate->getError());
        }

        $articleGoodModel = new ArticleGood();
        //获取用户已点赞的数据
        $goddessGood = $articleGoodModel->getGoodFromCache($this->user['id'], 1);
        //更新文章点赞数据
        if (in_array($aid, $goddessGood))
        {
            //取消点赞
            $articleGoodModel->delData($this->user['id'], $aid, ['aid' => $aid, 'uid' => $this->user['id'], 'type' => 1], 1);
        } else
        {
            //添加点赞
            $articleGoodModel->saveData($this->user, $aid, ['aid' => $aid, 'uid' => $this->user['id'], 'create_time' => time(), 'type' => 1], 1);
        }
        return show(config('code.success'), 'Good success.');

//        (new Article())->ArticleGood($map);
//
//        return show(config('code.success'), '点赞成功');//Good success.
    }

    /**
     * 文章收藏接口
     * @return Json
     * @throws \Exception
     */
    public function collect()
    {
        $aid = input('param.id/d', 0);
        $articleCollectModel = new ArticleCollect();
        //获取用户已收藏的数据
        $collectIds = array_keys($articleCollectModel->getUserAllCollectFromCache($this->user['id'], 1));
        if (in_array($aid, $collectIds))
        {
            $articleCollectModel->delData($this->user['id'], 1, $aid);
        } else
        {
            $articleCollectModel->saveData($this->user['id'], $aid, 1);
        }
        return show(config('code.success'), '操作成功');
    }

    /**
     * 周运详情
     * @return \think\response\Json
     * @throws ApiException
     */
    public function fortune_week_detail()
    {
        $in_sign = input('param.in_sign/d', 1);// 默认为白羊座

        $data = (new Article())->getFortune('week', $in_sign);

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 月运详情
     * @return \think\response\Json
     * @throws ApiException
     */
    public function fortune_month_detail()
    {
        $in_sign = input('param.in_sign/d', 1);// 默认为白羊座

        $data = (new Article())->getFortune('month', $in_sign);

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 年运详情
     * @return \think\response\Json
     * @throws ApiException
     */
    public function fortune_year_detail()
    {
        $in_sign = input('param.in_sign/d', 1);// 默认为白羊座

        $data = (new Article())->getFortune('year', $in_sign);

        return show(config('code.success'), '加载成功', $data);
    }

    /**
     * 文章评论
     * @return Json
     * @throws \Exception
     */
    public function comment()
    {
        $id = input('param.id/d');
        $content = htmlspecialchars(input('param.content/s', ''));
        $content = trim($content);
        if (empty($content))
        {
            return show(config('code.error'), '评论内容不能为空');
        }
        if ($this->filter_words($content))
        {
            return show(config('code.error'), '含有敏感词汇');
        }
        if ($this->user['no_comment'])
        {
            return show(config('code.error'), '评论失败，已被禁止评论');
        }
        $type = 2;
        $data = [
            'aid' => $id,
            'content' => $content,
            'ucid' => $this->user['uc_id'],
            'uid' => $this->user['id'],
            'status' => 0
        ];
        $rec = $this->CommentModel->add_comment($this->user, $data, false);
        if ($rec)
        {
            if ($type === 1)
            {
                return show(config('code.error'), '当前评论中有敏感词');
            }
            $rec['vip'] = (new ZlUserVip())->getUserVipLevel($this->user['id']);
            return show(config('code.success'), '评论成功', $rec);
        }
        return show(config('code.error'), '不能重复评论');
    }

    /**
     * 文章评论点赞
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws \Exception
     */
    public function comment_good()
    {
//        $id = input('param.id/d');
        $commentid = input('param.commentid/d');

        $articleCommentGood = new ArticleCommentGood();
        //获取用户已点赞的数据,并更新评论点赞数据
        $goddessGood = $articleCommentGood->getGoodFromCache($this->user['id'], 1);
        if (in_array($commentid, $goddessGood))
        {
            //取消点赞
            $articleCommentGood->delData($this->user['id'], $commentid, ['comment_id' => $commentid, 'uid' => $this->user['id'], 'type' => 1], 1);
            return show(config('code.success'), 'Good cancel success.');
        }

       //添加点赞
        $articleCommentGood->saveData($this->user, $commentid, ['comment_id' => $commentid, 'uid' => $this->user['id'], 'create_time' => time(), 'type' => 1], 1);
        return show(config('code.success'), 'Good success.');

//        $comment = Db::table('wechatadmin.system_article_comment')
//            ->where(['aid' => $id, 'id' => $commentid])->find();
//
//        if ($comment === NULL)
//        {
//            return show(config('code.error'), '该评论不存在,请稍后重试');
//
//        } else
//        {
//            $good = Db::table('wechatadmin.system_comment_good')
//                ->where(['aid' => $id, 'ucid' => $this->user['uc_id'], 'comment_id' => $commentid])->find();
//            if ($good === NULL)
//            {
//                Db::table('wechatadmin.system_comment_good')
//                    ->insertGetId([
//                        'aid' => $id,
//                        'comment_id' => $commentid,
//                        'ucid' => $this->user['uc_id'],
//                        'create_time' => time(),
//                    ]);
//                Db::execute("UPDATE `wechatadmin`.`system_article_comment`  SET `goods`=`goods`+1  WHERE  `id` = {$commentid}");
//
//                //删除评论点赞缓存
//                Cache::rm('article_comment_good_' . $this->user['id']);
//                //删除评论详情缓存
//                Cache::rm('article_comment_' . $commentid);
//                return show(config('code.success'), 'Good success.');
//
//            } else
//            {
//                Db::table('wechatadmin.system_comment_good')
//                    ->where([
//                        'aid' => $id,
//                        'comment_id' => $commentid,
//                        'ucid' => $this->user['uc_id'],
//                    ])->delete();
//
//                Db::execute("UPDATE `wechatadmin`.`system_article_comment`  SET `goods`=`goods`-1  WHERE  `id` = {$commentid}");
//
//                //删除评论点赞缓存
//                Cache::rm('article_comment_good_' . $this->user['id']);
//                //删除评论详情缓存
//                Cache::rm('article_comment_' . $commentid);
//                return show(config('code.success'), 'Good cancel success.');
//
//            }
//
//        }
    }

    /**
     * 删除评论
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function comment_delete()
    {
        $id = input('param.id/d');

        //删除评论
        $res = (new \app\common\cachemodel\ArticleComment())->commentDel($this->user['id'], $id);

//        $comment = Db::table('wechatadmin.system_article_comment')
//            ->field('id')
//            ->where(['id' => $id, 'ucid' => $this->user['uc_id'], 'status' => 0])->find();
//
//        if ($comment !== NULL)
//        {
//            Db::table('wechatadmin.system_article_comment')->where('id', $id)->update(['status' => 2]);
//
//            Cache::rm('article_comment_' . $id);  // 删除对应评论内容缓存
//            Cache::rm('article_comment_good_' . $id); // 删除对应评论点赞缓存
//            Cache::rm('comment_reply_id_' . $id); //删除对应回复id数组
//            Cache::rm('user:reply:' . $this->user['id']); // 删除对应用户回复id数组
//        }

        if ($res)
        {
            return show(config('code.success'), 'Success.');
        }
        return show(config('code.error'), 'error.');
    }

    /**
     * 文章评论回复(自测ok)
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \Exception
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function reply()
    {
        $id = input('param.id/d');
        $commentid = input('param.commentid/d');
        $pid = input('param.pid/d');
        $content = htmlspecialchars(input('param.content/s', ''));
        $content = trim($content);
        if (empty($content))
        {
            return show(config('code.error'), '评论内容不能为空');
        }
        if ($this->filter_words($content))
        {
            return show(config('code.error'), '含有敏感词汇');
        }

        if ($this->user['no_comment'])
        {
            return show(config('code.error'), '评论失败，已被禁止评论');
        }

        $data = [
            'aid' => $id,
            'comment_id' => $commentid,
            'create_time' => time(),
            'pid' => $pid,
            'content' => $content,
            'ucid' => $this->user['uc_id'],
            'uid' => $this->user['id'],
            'status' => 0
        ];
        $reply = $this->ReplyModel->add_reply($this->user, $data, false);

        if (isset($reply['uid']) && $reply['uid'] == $this->user['id'])
        {
            Cache::rm('read_reply_' . $this->user['id']);
        }

        if ($reply)
        {
            $reply['vip'] = (new ZlUserVip())->getUserVipLevel($this->user['id']);
            return show(config('code.success'), 'Reply success.', $reply);
        } else
        {
            return show(config('code.error'), '回复失败,请稍后再试');
        }

//        $reply = Db::table('wechatadmin.system_comment_reply')
//            ->where(['aid' => $id, 'comment_id' => $commentid, 'ucid' => $this->user['uc_id'], 'content' => $content, 'pid' => $pid, 'status' => 0])
//            ->find();
//
//        // 非重复回复  发表回复
//        if ($reply === NULL) {
//            if ($rid = Db::table('wechatadmin.system_comment_reply')
//                ->insertGetId([
//                    'aid' => $id,
//                    'comment_id' => $commentid,
//                    'ucid' => $this->user['uc_id'],
//                    'pid' => $pid,
//                    'content' => $content,
//                    'create_time' => time()
//                ])) {
//                Db::table('wechatadmin.system_article_comment')->where(['id' => $commentid, 'aid' => $id])->setInc('reply');
//                // 针对评论的回复
//                if ($pid == 0) {
//                    $reply = Db::table('wechatadmin.system_comment_reply')->alias('cr')
//                        ->field('cr.id,cr.content,cr.status,cr.create_time,
//                        cr.pid,u.nickname nickname1,u.avatar,u2.nickname nickname2')
//                        ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
//                        ->join('wechatadmin.system_article_comment ac', 'ac.id=cr.comment_id', 'INNER')
//                        ->join('wechat_backup_07_18_14_43_00.app_user u2', 'u2.uc_id=ac.ucid', 'INNER')
//                        ->where(['cr.id' => $rid])
//                        ->find();
//                } // 针对回复的回复
//                else {
//                    $reply = Db::table('wechatadmin.system_comment_reply')->alias('cr')
//                        ->field('cr.id,cr.content,cr.status,cr.create_time,
//                        cr.pid,u.nickname nickname1,u.avatar,u2.nickname nickname2')
//                        ->join('wechatadmin.system_comment_reply cr2', 'cr.pid=cr2.id', 'INNER')
//                        ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
//                        ->join('wechat_backup_07_18_14_43_00.app_user u2', 'u2.uc_id=cr2.ucid', 'INNER')
//                        ->find($rid);
//                }
//
//                return json(['code' => 200, 'msg' => 'Reply success.', 'data' => $reply]);
//            }
//        } else {
//            return json(['code' => 11201, 'msg' => 'Do not repeat the comments.']);
//        }
    }

    /**
     * 评论列表(自测ok)
     * @return Json
     * @throws \Exception
     */
    public function comment_lists()
    {
        $aid = input('param.aid/d');
        $page = input('param.page/d', 1);
        // 缓存
        $data_list = (new ArticleComment())->getComments([
            'aid' => $aid,
            'page' => $page,
            'uc_id' => $this->user['uc_id'],
            'uid' => $this->user['id'],
        ]);

//        $data = Db::table('wechatadmin.system_article_comment')->alias('ac')
//            ->field('ac.id,ac.aid,ac.content,ac.status,ac.create_time,ac.goods,ac.reply,u.nickname,u.avatar,ac.ucid')
//            ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=ac.ucid', 'INNER')
//            ->where(['ac.aid' => $aid, 'ac.status' => 0, 'u.forbidden' => 0])
//            ->order('ac.is_top DESC, ac.id DESC')
//            ->paginate(10, false, ['page' => $page]);
//
//        $data_list = json_decode(json_encode($data), true);
//
//        foreach ($data_list['data'] as $k => $d) {
//            // 判断当前评论是否为自己的评论   前台显示删除按钮
//            if ($d['ucid'] == $this->user['uc_id']) $data_list['data'][$k]['is_owner'] = true;
//            else $data_list['data'][$k]['is_owner'] = false;
//            unset($data_list['data'][$k]['ucid']);
//
//            $data_list['data'][$k]['good_status'] = false;
//            $good = Db::table('wechatadmin.system_comment_good')
//                ->where(['aid' => $aid, 'ucid' => $this->user['uc_id'], 'comment_id' => $d['id']])
//                ->find();
//
//            if ($good != null) $data_list['data'][$k]['good_status'] = true;
//
//            $reply_list = null;
//
//            $reply_list = Db::table('wechatadmin.system_comment_reply')->alias('cr')
//                ->field('cr.id,cr.content,cr.status,cr.create_time,cr.pid,cr.ucid,u.nickname nickname1,u2.nickname nickname2')
//                ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
//                ->join('wechatadmin.system_article_comment ac', 'ac.id=cr.comment_id', 'RIGHT')
//                ->join('wechat_backup_07_18_14_43_00.app_user u2', 'u2.uc_id=ac.ucid', 'INNER')
//                ->where(['cr.comment_id' => $d['id'], 'cr.status' => 0, 'u.forbidden' => 0, 'u2.forbidden' => 0])
//                ->limit(3)
//                ->order('cr.id DESC')
//                ->select();
//
//            $reply_list = json_decode(json_encode($reply_list), true);
//
//            if (!empty($reply_list)) {
//                foreach ($reply_list as $k2 => $rl) {
//                    if ($rl['pid'] != 0) {
//                        // 上级的昵称
//                        $new_nickname = Db::table('wechatadmin.system_comment_reply')
//                            ->alias('cr')
//                            ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', "INNER")
//                            ->field('nickname')
//                            ->where('cr.id', $rl['pid'])
//                            ->find();
//                        $reply_list[$k2]['nickname2'] = $new_nickname['nickname'];
//                    }
//                }
//            }
//
//
//            $data_list['data'][$k]['reply_list'] = $reply_list;
//        }

        return show(config('code.success'), '操作成功', $data_list);
    }

    /**
     * 查看全部回复(自测ok)
     * @return Json
     */
    public function reply_lists()
    {
        $commentid = input('param.commentid/d');
        $page = input('param.page/d', 1);
        // 缓存
        $data = $this->ReplyModel->getReplyLists(['ac_id' => $commentid], $page);
        return show(200, 'ok', $data);

//        $data = Db::table('wechatadmin.system_comment_reply')->alias('cr')
//            ->field('cr.id,cr.content,cr.status,cr.create_time,cr.pid,
//            u.avatar,u.nickname nickname1,u2.nickname nickname2')
//            ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
//            ->join('wechatadmin.system_article_comment ac', 'ac.id=cr.comment_id', 'RIGHT')
//            ->join('wechat_backup_07_18_14_43_00.app_user u2', 'u2.uc_id=ac.ucid', 'INNER')
//            ->where("cr.comment_id=$commentid AND cr.status=0 AND u.forbidden=0 AND u2.forbidden=0")
//            ->order('cr.id DESC')
//            ->paginate(10, false, ['query' => request()->param()])->toArray();
//
//        if (is_array($data['data']) && !empty($data['data'])) {
//            foreach ($data['data'] as $k => $d) {
//                // 针对回复的回复
//                if ($d['pid'] != 0) {
//                    $nickname1 = Db::table('wechatadmin.system_comment_reply')->alias('cr')
//                        ->field('u.nickname')
//                        ->join('wechat_backup_07_18_14_43_00.app_user u', 'u.uc_id=cr.ucid', 'INNER')
//                        ->where("cr.id={$d['pid']} AND u.forbidden=0")
//                        ->find();
//                    $data['data'][$k]['nickname2'] = $nickname1['nickname'];
//                }
//            }
//            return show(200, 'ok', $data);
//        } else {
//            $data = [
//                "total" => 0,
//                "per_page" => 10,
//                "current_page" => 1,
//                "last_page" => 0,
//                "data" => []
//            ];
//            return show(200, 'ok', $data);
//        }
    }

    /**
     * 回复我的(自测ok)
     * @return \think\response\Json
     * @throws \Exception
     */
    public function reply_me()
    {
        $page = input('page/d', 1);

        // 回复我的数据
        $data = (new ArticleCommentReply())->reply_me(['uc_id' => $this->user['uc_id'], 'uid' => $this->user['id'], 'page' => $page]);

        return show(config('code.success'), '操作成功', $data);

    }

    /**
     * 过滤敏感词汇
     * @param $content
     * @return bool
     */
    protected function filter_words($content)
    {
        $words = config('words');
        $status = false;
        foreach ($words as $w) if (strpos($content, $w) !== false) $status = true;
        if (in_array($content, $words)) $status = true;
        return $status;
    }
}
